/**   
 * @Copyright:  成都北诺星科技有限公司  All rights reserved.Notice 官方网站：http://www.beinuoxing.com
 */
package com.zhihuixingguang.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json转换工具类
 * @author wangmingwei
 *
 */
public abstract class JSONUtil {

	private static final ObjectMapper m = new ObjectMapper();

	/**
	 * 将对象转换成json，
	 * @param o
	 * @return 返回一个json字符串，并且不带格式化的。
	 */
	public static String toJSONString(Object o) {
		return toJSONString(o, false);
	}
	
	/**
	 * 将对象换砖成json
	 * @param o 转换的对象
	 * @param format  是否格式化。
	 * @return 返回json字符串，如果format为true，则返回格式化后的json字符串
	 */
	public static String toJSONString(Object o,boolean format) {
		try {
			m.setSerializationInclusion(Include.NON_EMPTY);
			if(format) {
				return m.writerWithDefaultPrettyPrinter().writeValueAsString(o);
			}
			return m.writeValueAsString(o);
		} catch (JsonProcessingException e) {
			throw new RuntimeException("对象转json失败", e);
		}
	}

	public static <T> T parseObject(String jsonString, Class<T> elementClasses) {
		m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		try {
			return m.readValue(jsonString, elementClasses);
		} catch (IOException e) {
			throw new RuntimeException("json 解析错误", e);
		}
	}

	public static <T> List<T> parseArray(String jsonString, Class<T> elementClasses) {
		m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		JavaType javaType = m.getTypeFactory().constructParametricType(ArrayList.class, elementClasses);
		try {
			return m.readValue(jsonString, javaType);
		} catch (IOException e) {
			throw new RuntimeException("json 解析错误", e);
		}
	}

}
